package com.saas.demo.comman;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: demo
 * @description: 全局拦截器
 * @author: guoxh
 * @create: 2019-01-25 13:51
 **/
@Slf4j
@Component
public class Interceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.debug("此次访问的接口：" + url);
        CommonParam.getInstance().setStartTime(System.currentTimeMillis());
        int tenantId = request.getIntHeader("tenantId");
        CommonParam.getInstance().setTenantId(tenantId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        long startTime = CommonParam.getInstance().getStartTime();
        long endTime = System.currentTimeMillis();
        double execTime = (endTime - startTime) / 1000.00;
        String method = ((HandlerMethod) handler).getMethod().toString().split("\\s")[2];//\s正则元字符
        log.debug("{} - execution time：{}s", method.substring(0, method.indexOf('(')), String.format("%.3f", execTime));
        //使用完线程共享变量后,显示调用remove方法清除线程共享变量
        CommonParam.remove();
    }
}
